extends Node

enum Bus{
	MASTER,
	BGM,
	SFX,
}

const BGM_BUS = "BGM"
const SFX_BUS = "SFX"
const EXBGM_BUS = "EXBGM"

var bgm_audio_player_count: int = 2
var cur_bgm_player_index:int = 0
var bgm_players: Array[AudioStreamPlayer]

var sfx_audio_player_count: int = 6
var sfx_players: Array[AudioStreamPlayer]
var music_fade_duration:float =1.0

func _ready():
	init_bgm_audio_manager()
	init_sfx_audio_mananger()
	
#初始化背景音乐播放器
func init_bgm_audio_manager():
	for i in sfx_audio_player_count:
		var audio_player:=AudioStreamPlayer.new()
		audio_player.bus = SFX_BUS
		add_child(audio_player)
		sfx_players.append(audio_player)

#初始化音效播放器
func init_sfx_audio_mananger():
	for i in bgm_audio_player_count:
		var audio_player:=AudioStreamPlayer.new()
		audio_player.process_mode = Node.PROCESS_MODE_ALWAYS
		audio_player.bus = BGM_BUS
		add_child(audio_player)
		bgm_players.append(audio_player)
	
#播放背景音乐
func play_bgm(_audio:AudioStream):
	var cur_audio_player := bgm_players[cur_bgm_player_index]
	if cur_audio_player.stream == _audio:
		return
	var empty_audio_player_index = 0 if cur_bgm_player_index == 1 else 1
	var empty_audio_player:= bgm_players[empty_audio_player_index]
	var cur_position = cur_audio_player.get_playback_position()
	empty_audio_player.stream= _audio
	var pos = cur_audio_player.get_playback_position()

	play_and_fade_in(empty_audio_player,pos)
	fade_out_and_stop(cur_audio_player)
	cur_bgm_player_index = empty_audio_player_index

#播放音效
func play_sfx(_audio:AudioStream,_is_random_pitch:bool = false):
	var pitch := 1.0 
	if _is_random_pitch:
		pitch = randf_range(0.9,1.1)
	
	for i in sfx_audio_player_count:
		var sfx_audio_player :=sfx_players[i]
		if not sfx_audio_player.playing:
			sfx_audio_player.stream=_audio
			sfx_audio_player.pitch_scale = pitch
			sfx_audio_player.play()
			break

#设置音量
func set_volume(bus_index:Bus,v:float):
	var db = linear_to_db(v)
	AudioServer.set_bus_volume_db(bus_index,db)

#渐入方法	
func play_and_fade_in(_audio_player:AudioStreamPlayer,pos:float):
	_audio_player.play(pos)
	var tween:Tween = create_tween()
	tween.tween_property(_audio_player,"volume_db",0,music_fade_duration)
	
#渐出方法
func fade_out_and_stop(_audio_player:AudioStreamPlayer):
	var tween:Tween = create_tween()
	tween.tween_property(_audio_player,"volume_db",-40,music_fade_duration)
	await tween.finished
	_audio_player.stop()
	_audio_player.stream = null
